package com.sunchangpeng.server.nio.basic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

public class Handler {
    private static final Logger LOGGER = LoggerFactory.getLogger(Handler.class);

    public void handle(SelectionKey selectionKey) throws IOException {
        SocketChannel sc = (SocketChannel) selectionKey.channel();
        send(sc, encode(compute(decode(read(sc)))));
    }

    public byte[] read(SocketChannel sc) throws IOException {
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        int readBytes = sc.read(readBuffer);
        if (readBytes > 0) {
            readBuffer.flip();
            byte[] rBytes = new byte[readBuffer.remaining()];
            readBuffer.get(rBytes);
            return rBytes;
        }

        return null;
    }

    public String decode(byte[] bytes) throws UnsupportedEncodingException {
        return new String(bytes, "UTF-8");
    }

    public String compute(String body) {
        LOGGER.info("The time server receive order : {}", body);
        return String.valueOf(System.currentTimeMillis());
    }

    public byte[] encode(String body) {
        return body.getBytes();
    }

    public void send(SocketChannel sc, byte[] bytes) throws IOException {
        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        writeBuffer.put(bytes);
        writeBuffer.flip();
        sc.write(writeBuffer);
    }
}
